#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

#include "ngx_mem_pool.h"

struct Foo {
    char* p1;
    FILE* p2;
};

void f1(void* p) {
    std::cout << "free(p)" << std::endl;
    free(p);
}
void f2(void* p) {
    std::cout << "fclose(p)" << std::endl;
    fclose((FILE*)p);
}

int main() {
    ngx_mem_pool mempool(512);

    char* p1 = (char*)mempool.ngx_palloc(128);  // 小块内存池上分配
    if (!p1) {
        std::cerr << "ngx_palloc 128 bytes failed." << std::endl;
        return -1;
    }

    Foo* f = (Foo*)mempool.ngx_palloc(sizeof(Foo) * 512);  // 大块内存池分配
    if (!f) {
        std::cerr << "ngx_palloc 512*" << sizeof(Foo) << " bytes failed."
                  << std::endl;
        return -1;
    }

    f->p1 = (char*)malloc(12);
    strcpy(f->p1, "hello,nginx");

    f->p2 = fopen("text.txt", "w");

    ngx_pool_cleanup_t* c1 = mempool.ngx_pool_cleanup_add(sizeof(char*));
    ngx_pool_cleanup_t* c2 = mempool.ngx_pool_cleanup_add(sizeof(FILE*));

    c1->handler = f1;
    c1->data = f->p1;

    c2->handler = f2;
    c2->data = f->p2;

    return 0;
}
